import { Ref } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { EChartsType } from 'echarts';

/**
 * 监听Echarts父级尺寸变化重载Echarts
 */
export function useEchartsResizeObserver(
  chartDom: Ref<EChartsType>,
  chartParentDom: Ref<Element>
): { observer: ResizeObserver } {
  // echarts重载防抖
  const throttledFn = useDebounceFn(() => {
    if (chartDom.value) chartDom.value.resize();
  });

  // 监听 chart 父元素尺寸的变化
  function resizeObserver() {
    const element = chartParentDom.value;
    const observer = new ResizeObserver((entries) => {
      for (const entry of entries) {
        throttledFn().then(); // 防抖
      }
    });
    observer.observe(element);
    return observer;
  }
  const observer: ResizeObserver = resizeObserver();

  return {
    observer,
  };
}
